//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package project_doc_dao

import (
	"context"
	"fmt"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type ContentHistoryDbItem struct {
	HistoryId    string `bson:"_id"`
	DocId        string `bson:"docId"`
	TimeStamp    int64  `bson:"timeStamp"`
	Content      string `bson:"content"`
	UpdateUserId string `bson:"updateUserId"`
}

type HistoryAndTimeStamp struct {
	HistoryId    string
	TimeStamp    int64
	UpdateUserId string
}

type _ContentHistoryDao struct {
	mc *mongo.Collection
}

func newContentHistoryDao(db *mongo.Database) (*_ContentHistoryDao, error) {
	mc := db.Collection(db_ns.DB_NS_PROJECT_DOC + "content_history")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"docId", 1}, {"timeStamp", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_ContentHistoryDao{mc: mc}, nil
}

func (db *_ContentHistoryDao) Insert(ctx context.Context, dbItem *ContentHistoryDbItem) error {
	dbItem.HistoryId = db.genHistoryId(dbItem.DocId, dbItem.TimeStamp)
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_ContentHistoryDao) genHistoryId(docId string, timeStamp int64) string {
	return fmt.Sprintf("%s:%d", docId, timeStamp)
}

func (db *_ContentHistoryDao) RemoveByTimeStamp(ctx context.Context, docId string, timeStampList []int64) error {
	if len(timeStampList) == 0 {
		return nil
	}
	historyIdList := []string{}
	for _, timeStamp := range timeStampList {
		historyId := db.genHistoryId(docId, timeStamp)
		historyIdList = append(historyIdList, historyId)
	}
	_, err := db.mc.DeleteMany(ctx, bson.M{"_id": bson.M{"$in": historyIdList}, "docId": docId})
	return err
}

func (db *_ContentHistoryDao) RemoveByDoc(ctx context.Context, docId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"docId": docId})
	return err
}

func (db *_ContentHistoryDao) ListLastTimeStamp(ctx context.Context, docId string, limit int64) ([]HistoryAndTimeStamp, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"docId": docId}, options.Find().SetProjection(bson.M{"_id": 1, "timeStamp": 1, "updateUserId": 1}).SetLimit(limit).SetSort(bson.M{"timeStamp": -1}))
	if err != nil {
		return nil, err
	}
	tmpList := []*ContentHistoryDbItem{}
	err = cursor.All(ctx, &tmpList)
	if err != nil {
		return nil, err
	}
	retList := []HistoryAndTimeStamp{}
	for _, tmpItem := range tmpList {
		retList = append(retList, HistoryAndTimeStamp{
			HistoryId:    tmpItem.HistoryId,
			TimeStamp:    tmpItem.TimeStamp,
			UpdateUserId: tmpItem.UpdateUserId,
		})
	}
	return retList, nil
}

func (db *_ContentHistoryDao) Get(ctx context.Context, historyId, docId string) (*ContentHistoryDbItem, error) {
	retItem := &ContentHistoryDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": historyId, "docId": docId}).Decode(&retItem)
	return retItem, err
}
